// pages/merchantManagement/index.js
const app = getApp();

Page({
  data: {
    // 用户信息
    userInfo: {},
    logged: false,
    phoneNumber: '',
    schoolName: '', // 学校名称
    
    // 权限控制
    permissions: {
      PPacakgePickUp: false,          // 快递订单权限
      PSnackPickup: false,            // 零食代买权限
      PWashShoes: false,              // 洗鞋订单权限
      PWashClothes: false,           // 洗衣订单权限
      PPaoTui: false,                 // 跑腿权限
      PPrintBlackAndWhite: false,     // 打印订单权限
      allOrders: false,               // 所有订单权限
    },
    
    // 产品类型配置（动态从云函数获取）
    productTypes: [],
    // 默认产品类型（作为备用）
    defaultProductTypes: [
      { 
        id: 'PPacakgePickUp', 
        name: '快递代取', 
        color: '#4CAF50'
      },
      { 
        id: 'PSnackPickup', 
        name: '零食代买', 
        color: '#F06292'
      },
      { 
        id: 'PWashShoes', 
        name: '洗鞋服务', 
        color: '#2196F3'
      },
      { 
        id: 'PWashClothes', 
        name: '洗衣服务', 
        color: '#FF9800'
      },
      { 
        id: 'PPaoTui', 
        name: '跑腿服务', 
        color: '#9C27B0'
      },
      { 
        id: 'PPrintBlackAndWhite', 
        name: '打印服务', 
        color: '#607D8B'
      },
      { 
        id: 'allOrders', 
        name: '所有订单', 
        color: '#795548'
      }
    ],
    
    // 当前选中的产品类型
    selectedProductType: 'PPacakgePickUp',
    selectedProductInfo: {}, // 当前选中产品的完整信息
    showProductDropdown: false, // 是否显示下拉菜单
    filteredProductTypes: [], // 过滤后的产品类型列表
    
    // 订单状态筛选
    orderStatusOptions: [
      { value: 'all', text: '全部' },
      { value: 'unclaimed', text: '未领取' },
      { value: 'claimed', text: '已领取' },
      { value: 'inProgress', text: '进行中' },
      { value: '退款中', text: '退款中' },
      { value: 'completed', text: '已完成' },
      { value: 'refunded', text: '已退款' }
    ],
    selectedOrderStatusIndex: 0, // 默认选择"全部"
    showOrderStatusDropdown: false, // 是否显示订单状态下拉菜单
    
    // 页面状态
    activeTab: 'orders', // orders, complaints
    isLoading: false,
    
    // 订单数据
    orders: [],
    total: 0,
    page: 1,
    pageSize: 20,
    
    // 订单统计数据
    orderStatistics: {
      totalOrders: 0,        // 订单总数
      inProgressOrders: 0,   // 进行中订单数
      completedOrders: 0,    // 已完成订单数
      refundedOrders: 0,     // 已退款订单数
      claimedOrders: 0,      // 已领取订单数
      unclaimedOrders: 0,    // 未领取订单数
      todayRefundingOrders: 0, // 今日退款中订单数
    },
    
    
    // 投诉数据
    complaints: [],
    complaintTotal: 0,
    
    // 展开状态
    expandedMap: {},
    userExpandedOrders: {},
    
    // 搜索相关
    searchKeyword: '',
    
    
    // 退款相关
    showRefundModal: false,
    refundData: {
      orderId: '',
      totalAmount: 0,
      orderStatus: '',     // 新增：订单状态
      refundType: 'full',  // 'full'、'partial' 或 'reject'
      refundAmount: 0,
      refundReason: '',
      rejectReason: ''     // 新增：拒绝原因
    }
  },

  // 状态顺序表
  STATUS_ORDER: [
    "待取货",  // 索引 0
    "待入库",  // 索引 1
    "待清洗",  // 索引 2
    "待送达",  // 索引 3
    "已完成"   // 索引 4
  ],

  onLoad() {
    console.log('商家管理页面加载');
    this.initPage();
  },

  onShow() {
    console.log('商家管理页面显示');
    // 移除重复的用户信息加载，onLoad已经处理了
  },

  // 初始化产品下拉菜单
  initProductDropdown() {
    const { productTypes, selectedProductType, permissions } = this.data;
    
    // 过滤有权限的产品类型
    const filteredTypes = productTypes.filter(item => 
      permissions[item.id] || item.id === 'allOrders'
    );
    
    // 检查默认选择的产品是否有权限，如果没有则选择第一个有权限的产品
    let finalSelectedType = selectedProductType;
    if (!permissions[selectedProductType] && selectedProductType !== 'allOrders') {
      finalSelectedType = filteredTypes.length > 0 ? filteredTypes[0].id : 'allOrders';
    }
    
    // 找到当前选中的产品信息
    const selectedProduct = productTypes.find(item => item.id === finalSelectedType) || 
                           productTypes.find(item => item.id === 'allOrders');
    
    this.setData({
      selectedProductType: finalSelectedType,
      filteredProductTypes: filteredTypes,
      selectedProductInfo: selectedProduct || {}
    });
  },

  // 初始化页面
  async initPage() {
    console.log('开始初始化页面');
    try {
      await this.loadUserInfoAndPermissions(); // 合并用户信息和权限加载
      this.loadSchoolName(); // 加载学校名称
      await this.fetchProductList(); // 获取动态产品列表
      this.initProductDropdown(); // 初始化产品下拉菜单（在获取产品列表后）
      this.loadComplaints();
      // 延迟加载订单，确保产品列表已经设置完成
      setTimeout(async () => {
        await this.loadOrders();
        await this.loadOrderStatistics(); // 加载订单统计数据
      }, 100);
      console.log('页面初始化完成');
    } catch (error) {
      console.error('页面初始化失败:', error);
    }
  },

  // 加载学校名称
  loadSchoolName() {
    try {
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolName = selectedAddress && selectedAddress.addressName ? selectedAddress.addressName : '';
      console.log('加载学校名称:', schoolName);
      this.setData({
        schoolName: schoolName
      });
    } catch (error) {
      console.error('加载学校名称失败:', error);
      this.setData({
        schoolName: ''
      });
    }
  },

  // 合并加载用户信息和权限（避免重复调用）
  loadUserInfoAndPermissions() {
    return new Promise((resolve) => {
      const openId = wx.getStorageSync('openId');
      if (!openId) {
        resolve();
        return;
      }

      wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getUserInfoRequest: { userId: openId }
        },
        success: (res) => {
          const userData = res.result.data;
          const merchantPermissions = userData.merchantPermission || [];
          
          // 设置用户信息
          this.setData({
            logged: !!userData.phone,
            phoneNumber: userData.phone || '',
            userInfo: userData
          });

          // 设置权限信息
          const updatedPermissions = {
            PPacakgePickUp: false,
            PSnackPickup: false,
            PWashShoes: false,
            PWashClothes: false,
            PPaoTui: false,
            PPrintBlackAndWhite: false,
            allOrders: false,
          };

          merchantPermissions.forEach((permission) => {
            if (updatedPermissions.hasOwnProperty(permission)) {
              updatedPermissions[permission] = true;
            }
          });

          this.setData({
            permissions: updatedPermissions
          });
          
          console.log('用户信息和权限加载完成');
          resolve();
        },
        fail: (err) => {
          console.error('获取用户信息和权限失败:', err);
          resolve();
        }
      });
    });
  },

  // 保留原有方法以兼容其他可能的调用
  loadUserInfo() {
    return this.loadUserInfoAndPermissions();
  },

  loadPermissions() {
    return this.loadUserInfoAndPermissions();
  },

  // 切换产品类型下拉菜单
  toggleProductDropdown() {
    this.setData({
      showProductDropdown: !this.data.showProductDropdown,
      showOrderStatusDropdown: false // 关闭其他下拉菜单
    });
  },

  // 切换订单状态下拉菜单
  toggleOrderStatusDropdown() {
    this.setData({
      showOrderStatusDropdown: !this.data.showOrderStatusDropdown,
      showProductDropdown: false // 关闭其他下拉菜单
    });
  },

  // 产品类型选择
  selectProductType(e) {
    const productType = e.currentTarget.dataset.type;
    console.log('========== selectProductType 被调用 ==========');
    console.log('选择的产品类型:', productType);
    
    // 找到选中的产品信息
    const selectedProduct = this.data.productTypes.find(item => item.id === productType);
    
    this.setData({
      selectedProductType: productType,
      selectedProductInfo: selectedProduct || {},
      showProductDropdown: false, // 选择后关闭下拉菜单
      page: 1,
      orders: []
    });
    
    // 如果有搜索关键词，保持搜索状态
    const searchKeyword = this.data.searchKeyword;
    this.loadOrders(searchKeyword);
    
    // 重新加载订单统计数据
    this.loadOrderStatistics();
    
    // 更新投诉数据
    this.loadComplaints();
  },

  // 选择订单状态
  selectOrderStatus(e) {
    const index = e.currentTarget.dataset.index;
    console.log('选择订单状态:', this.data.orderStatusOptions[index].text);
    
    this.setData({
      selectedOrderStatusIndex: index,
      showOrderStatusDropdown: false, // 选择后关闭下拉菜单
      page: 1,
      orders: []
    });
    
    // 重新加载订单数据（接口筛选）
    const searchKeyword = this.data.searchKeyword;
    this.loadOrders(searchKeyword);
  },


  // 点击页面其他地方关闭下拉菜单
  onPageTap() {
    if (this.data.showProductDropdown || this.data.showOrderStatusDropdown) {
      this.setData({
        showProductDropdown: false,
        showOrderStatusDropdown: false
      });
    }
  },

  // 搜索输入处理
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({
      searchKeyword: keyword
    });
  },

  // 搜索订单
  searchOrder() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入订单号',
        icon: 'none'
      });
      return;
    }
    
    console.log('========== 搜索订单开始 ==========');
    console.log('搜索关键词:', keyword);
    console.log('搜索前订单数量:', this.data.orders.length);
    
    this.setData({
      page: 1,
      orders: []
    });
    
    console.log('清空订单列表，准备搜索');
    this.loadOrders(keyword);
  },

  // 扫码功能
  scanCode() {
    wx.scanCode({
      success: (res) => {
        console.log('扫码结果:', res.result);
        this.setData({
          searchKeyword: res.result,
          page: 1,
          orders: []
        });
        this.loadOrders(res.result);
      },
      fail: (err) => {
        console.error('扫码失败:', err);
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab
    });
    
    if (tab === 'complaints') {
      this.loadComplaints();
    }
  },

  // 加载订单数据
  async loadOrders(searchKeyword = null) {
    console.log('========== loadOrders 被调用 ==========');
    console.log('当前参数:', {
      page: this.data.page,
      pageSize: this.data.pageSize,
      selectedProductType: this.data.selectedProductType,
      searchKeyword: searchKeyword,
      isLoading: this.data.isLoading
    });
    
    if (this.data.isLoading) {
      console.log('正在加载中，跳过本次调用');
      return;
    }
    
    this.setData({ isLoading: true });
    
    try {
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 根据订单状态设置筛选参数
      const selectedOrderStatus = this.data.orderStatusOptions[this.data.selectedOrderStatusIndex].value;
      let requestParams = {
        page: this.data.page,
        pageSize: this.data.pageSize,
        orderType: this.data.selectedProductType === 'allOrders' ? null : this.data.selectedProductType,
        schoolCode: schoolCode,
        orderId: searchKeyword,
        excludeRefundedOrders: false
      };

      // 根据订单状态添加相应参数
      if (selectedOrderStatus === 'unclaimed') {
        requestParams.noRiderId = true; // 未领取订单
        requestParams.excludeRefundedOrders = true;
      } else if (selectedOrderStatus === 'claimed') {
        requestParams.hasRiderId = true; // 已领取订单
        requestParams.excludeRefundedOrders = true;
      } else if (selectedOrderStatus === 'inProgress') {
        requestParams.orderStatus = 'inProgress';
        requestParams.hasRiderId = true;
        requestParams.excludeRefundedOrders = true;
      } else if (selectedOrderStatus === '退款中') {
        requestParams.orderStatus = '退款中';
      } else if (selectedOrderStatus === 'completed') {
        requestParams.orderStatus = 'done';
      } else if (selectedOrderStatus === 'refunded') {
        requestParams.orderStatus = 'refunded';
      }
      // 'all' 状态不添加额外参数

      console.log('准备调用云函数，参数:', requestParams);

      const res = await wx.cloud.callFunction({
        name: "xiaoBangCommonFunction",
        data: {
          getOrderListForManageRequest: requestParams
        },
      });

      if (res.result.code === 200) {
        let { orders, total } = res.result.data;
        
        console.log('云函数返回结果:', {
          code: res.result.code,
          ordersCount: orders.length,
          total: total,
          searchKeyword: searchKeyword
        });
        
        // 处理订单数据
        orders.forEach(order => {
          order.orderType = this.getOrderTypeByProductId(order);
          order.paoTuiPickupAddress = order.pao_tui_pickup_address;
          order.paoTuiPickupTime = order.pao_tui_pickup_time;
          order.paoTuiDeliveryAddress = order.pao_tui_delivery_address;
          order.paoTuiDeliveryTime = order.pao_tui_delivery_time;
          order.paoTuiNote = order.paoTuiNote;
          
          // 处理快递代取信息
          if (order.packagePickupInfos && order.packagePickupInfos.length > 0) {
            order.packagePickupInfos = order.packagePickupInfos.map(info => ({
              pickupAddress: info.pickupAddress || info.pickup_address,
              pickupCode: info.pickupCode || info.pickup_code,
              pickupSize: info.pickupSize || info.pickup_size,
              photos: info.photos || []
            }));
          }
          
          // 处理洗鞋图片信息
          order.beforeCleaningPhotos = order.beforeCleaningPhotos || order.before_cleaning_photos || [];
          order.afterCleaningPhotos = order.afterCleaningPhotos || order.after_cleaning_photos || [];
          
          // 处理送达图片信息（所有产品类型通用）
          order.deliveredPhotos = order.deliveredPhotos || order.delivered_photos || [];
          
          // 处理退款信息（兼容历史数据）
          const rawRefundAmount = order.refundAmount || order.refund_amount || 0;
          order.refundAmount = this.formatAmount(rawRefundAmount); // 格式化金额，避免浮点数精度问题
          order.refundReason = order.refundReason || order.refund_reason || '';
          order.refundType = order.refundType || order.refund_type || '';

          
          // 兼容历史数据：如果订单状态是已退款但没有refund_type字段，自动设置
          if (order.orderStatus === '已退款' && !order.refundType) {
            order.refundType = 'full';
          } else if (order.orderStatus === '部分退款' && !order.refundType) {
            order.refundType = 'partial';
          }

        });

        // 直接使用后端返回的已筛选数据
        this.setData({
          orders: this.data.page === 1 ? orders : [...this.data.orders, ...orders],
          total: total,
        });
      } else {
        wx.showToast({
          title: res.result.message || "获取订单失败",
          icon: "none",
        });
      }
    } catch (error) {
      console.error("获取订单失败：", error);
      wx.showToast({
        title: "获取订单失败，请稍后重试",
        icon: "none",
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  // 加载订单统计数据
  async loadOrderStatistics() {
    try {
      console.log('========== loadOrderStatistics 开始加载订单统计数据 ==========');
      
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 获取今天的日期 (YYYY-MM-DD 格式) - 使用本地时区，避免 UTC 与数据库时区不一致导致统计偏移
      const now = new Date();
      const todayStr = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0');

      const requestParams = {
        schoolCode: schoolCode,
        orderType: this.data.selectedProductType === 'allOrders' ? null : this.data.selectedProductType,
        date: todayStr  // 添加今天的日期参数
      };

      console.log('订单统计请求参数:', requestParams);

      const res = await wx.cloud.callFunction({
        name: "xiaoBangCommonFunction",
        data: {
          getOrderStatisticsRequest: requestParams
        },
      });

      if (res.result.code === 200) {
        const statistics = res.result.data;
        console.log('订单统计数据:', statistics);
        
        this.setData({
          orderStatistics: statistics
        });
      } else {
        console.error('获取订单统计数据失败:', res.result.message);
      }
    } catch (error) {
      console.error("获取订单统计数据失败：", error);
    }
  },

  // 加载投诉数据
  async loadComplaints() {
    try {
      console.log('========== loadComplaints 开始加载投诉数据 ==========');
      console.log('当前选中的产品类型:', this.data.selectedProductType);
      
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      const res = await wx.cloud.callFunction({
        name: "xiaoBangCommonFunction",
        data: {
          getComplaintListRequest: {
            page: 1,
            pageSize: 50,
            schoolCode: schoolCode,
            productId: this.data.selectedProductType === 'allOrders' ? null : this.data.selectedProductType
          }
        },
      });

      console.log('投诉数据云函数返回结果:', res.result);

      if (res.result.code === 200) {
        const { complaints, total } = res.result.data;
        console.log('获取到投诉数据:', {
          complaintsCount: complaints.length,
          total: total,
          selectedProductType: this.data.selectedProductType
        });
        
        this.setData({
          complaints: complaints || [],
          complaintTotal: total || 0
        });
      } else {
        console.error('获取投诉数据失败:', res.result.message);
      }
    } catch (error) {
      console.error("获取投诉数据失败：", error);
    }
  },

  // 获取订单类型
  getOrderTypeByProductId(order) {
    const productId = order.order_item?.product_id;
    const typeMap = {
      'PPacakgePickUp': '快递代取',
      'PSnackPickup': '零食代买',
      'PWashShoes': '洗鞋服务',
      'PWashClothes': '洗衣服务',
      'PPaoTui': '跑腿服务',
      'PPrintBlackAndWhite': '打印服务'
    };
    return typeMap[productId] || '未知服务';
  },

  // 格式化日期
  formatDate(dateStr) {
    try {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '';
      
      // 格式化为 YYYY-MM-DD HH:mm:ss
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {
      console.warn('日期格式化失败:', dateStr, error);
      return '';
    }
  },

  // 切换订单展开状态
  toggleOrderExpand(e) {
    const orderId = e.currentTarget.dataset.id;
    const expandedMap = { ...this.data.expandedMap };
    const userExpandedOrders = { ...this.data.userExpandedOrders };
    
    if (expandedMap[orderId]) {
      delete expandedMap[orderId];
      delete userExpandedOrders[orderId];
    } else {
      expandedMap[orderId] = true;
      userExpandedOrders[orderId] = true;
    }
    
    this.setData({
      expandedMap,
      userExpandedOrders
    });
  },

  // 阻止事件冒泡
  stopPropagation(e) {
    // 空函数，仅用于阻止事件冒泡
  },

  // 打印订单 - 单张
  printOrder1(e) {
    const { id } = e.currentTarget.dataset; // 获取订单 ID
    this.print(id, 1);
  },

  // 打印订单 - 两张
  printOrder2(e) {
    const { id } = e.currentTarget.dataset; // 获取订单 ID
    this.print(id, 2);
  },
  
  // 打印订单 - 三张
  printOrder3(e) {
    const { id } = e.currentTarget.dataset; // 获取订单 ID
    this.print(id, 3);
  },

  // 核心打印方法
  print(orderId, times) {
    // 验证订单ID
    if (!orderId) {
      wx.showToast({
        title: '订单信息获取失败',
        icon: 'none',
      });
      return;
    }

    // 验证订单是否存在
    const order = this.data.orders.find((item) => item.orderId === orderId);
    if (!order) {
      wx.showToast({
        title: '订单信息未找到',
        icon: 'none',
      });
      return;
    }

    // 显示确认对话框
    wx.showModal({
      title: '确认打印',
      content: `确认打印订单 ${orderId}，共 ${times} 张？`,
      success: (res) => {
        if (res.confirm) {
          this.executePrint(orderId, times);
        }
      }
    });
  },

  // 执行打印操作
  executePrint(orderId, times) {
    // 显示加载提示
    wx.showLoading({
      title: '正在打印...',
    });

    // 调用云函数进行打印
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction', // 云函数名称
      data: {
        "printTicketRequest": {
          orderId: orderId, // 将订单信息传递给云函数
          times: times
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('云函数调用成功:', res);
        
        const data = res.result;
        if (data.ret === 0) {
          wx.showToast({
            title: '打印成功',
            icon: 'success',
          });
        } else {
          wx.showToast({
            title: `打印失败: ${data.msg}`,
            icon: 'none',
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('云函数调用失败:', err);
        wx.showToast({
          title: '打印失败，请检查网络',
          icon: 'none',
        });
      },
    });
  },

  // 确认入库
  stockIn(e) {
    const { id: orderId } = e.currentTarget.dataset;
    console.log('确认入库:', orderId);
    
    // 验证订单是否存在
    const order = this.data.orders.find((item) => item.orderId === orderId);
    if (!order) {
      wx.showToast({ title: '订单信息未找到', icon: 'none' });
      return;
    }

    // 调用状态更新处理，目标状态为 "待清洗"
    this.handleStatusUpdate(order, "待清洗");
  },

  // 清洗完成
  cleaned(e) {
    const { id: orderId } = e.currentTarget.dataset;
    console.log('清洗完成:', orderId);
    
    // 验证订单是否存在
    const order = this.data.orders.find((item) => item.orderId === orderId);
    if (!order) {
      wx.showToast({ title: '订单信息未找到', icon: 'none' });
      return;
    }

    // 调用状态更新处理，目标状态为 "待送达"
    this.handleStatusUpdate(order, "待送达");
  },

  // 单个订单刷新方法
  async refreshSingleOrder(orderId) {
    try {
      // 从缓存获取选中的学校代码
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 调用云函数查询单个订单
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getOrderListForManageRequest: {
            orderId: orderId,
            schoolCode: schoolCode
          }
        },
      });

      if (res.result.code === 200) {
        const { orders } = res.result.data;
        if (orders && orders.length > 0) {
          const updatedOrder = orders[0];
          
          // 处理订单数据（复用 loadOrders 中的数据处理逻辑）
          updatedOrder.orderType = this.getOrderTypeByProductId(updatedOrder);
          updatedOrder.paoTuiPickupAddress = updatedOrder.pao_tui_pickup_address;
          updatedOrder.paoTuiPickupTime = updatedOrder.pao_tui_pickup_time;
          updatedOrder.paoTuiDeliveryAddress = updatedOrder.pao_tui_delivery_address;
          updatedOrder.paoTuiDeliveryTime = updatedOrder.pao_tui_delivery_time;
          updatedOrder.paoTuiNote = updatedOrder.paoTuiNote;
          
          // 处理快递代取信息
          if (updatedOrder.packagePickupInfos && updatedOrder.packagePickupInfos.length > 0) {
            updatedOrder.packagePickupInfos = updatedOrder.packagePickupInfos.map(info => ({
              pickupAddress: info.pickupAddress || info.pickup_address,
              pickupCode: info.pickupCode || info.pickup_code,
              pickupSize: info.pickupSize || info.pickup_size,
              photos: info.photos || []
            }));
          }
          
          // 处理洗鞋图片信息
          updatedOrder.beforeCleaningPhotos = updatedOrder.beforeCleaningPhotos || updatedOrder.before_cleaning_photos || [];
          updatedOrder.afterCleaningPhotos = updatedOrder.afterCleaningPhotos || updatedOrder.after_cleaning_photos || [];
          
          // 处理送达图片信息
          updatedOrder.deliveredPhotos = updatedOrder.deliveredPhotos || updatedOrder.delivered_photos || [];
          
          // 处理退款信息
          const rawRefundAmount = updatedOrder.refundAmount || updatedOrder.refund_amount || 0;
          updatedOrder.refundAmount = this.formatAmount(rawRefundAmount);
          updatedOrder.refundReason = updatedOrder.refundReason || updatedOrder.refund_reason || '';
          updatedOrder.refundType = updatedOrder.refundType || updatedOrder.refund_type || '';

          // 更新本地订单列表中的对应订单
          const updatedOrders = this.data.orders.map(order => {
            if (order.orderId === orderId) {
              return updatedOrder;
            }
            return order;
          });

          this.setData({ orders: updatedOrders });
          
          // 刷新订单统计数据
          this.loadOrderStatistics();
          
          return true;
        }
      }
      return false;
    } catch (error) {
      console.error('刷新单个订单失败:', error);
      return false;
    }
  },

  // 通用状态更新处理
  async handleStatusUpdate(order, targetStatus) {
    const currentStatus = order.processStatus; // 当前状态（字符串）
    const currentIndex = this.STATUS_ORDER.indexOf(currentStatus); // 当前状态的索引
    const targetIndex = this.STATUS_ORDER.indexOf(targetStatus); // 目标状态的索引
    
    console.log('状态流转:', {
      currentStatus,
      targetStatus,
      currentIndex,
      targetIndex
    });
    
    // 如果状态不存在于映射中
    if (currentIndex === -1 || targetIndex === -1) {
      wx.showToast({
        title: '无效的状态流转',
        icon: 'none'
      });
      return;
    }

    // 判断状态流转类型
    if (targetIndex === currentIndex + 1) {
      // 相邻状态，直接流转
      console.log("相邻状态流转，直接更新");
      const success = await this.updateOrderStatus(order.orderId, targetStatus, `状态流转成功`);
      if (success) {
        // 刷新单个订单数据
        await this.refreshSingleOrder(order.orderId);
      }
    } else if (targetIndex > currentIndex + 1) {
      // 跳跃状态，弹窗确认
      wx.showModal({
        title: '确认跳跃状态',
        content: `当前状态为: ${currentStatus}，目标状态为: ${targetStatus}，是否确认跳跃流转？`,
        success: async (res) => {
          if (res.confirm) {
            const success = await this.updateOrderStatus(order.orderId, targetStatus, `状态跳跃成功`);
            if (success) {
              // 刷新单个订单数据
              await this.refreshSingleOrder(order.orderId);
            }
          }
        },
      });
    } else if (targetIndex < currentIndex) {
      // 逆转状态，弹窗确认
      wx.showModal({
        title: '确认逆转状态',
        content: `当前状态为: ${currentStatus}，目标状态为: ${targetStatus}，是否确认逆转？`,
        success: async (res) => {
          if (res.confirm) {
            const success = await this.updateOrderStatus(order.orderId, targetStatus, `状态逆转成功`);
            if (success) {
              // 刷新单个订单数据
              await this.refreshSingleOrder(order.orderId);
            }
          }
        },
      });
    }
  },

  // 复制文件URL
  copyFileUrl(e) {
    const { url } = e.currentTarget.dataset;
    wx.setClipboardData({
      data: url,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success'
        });
      }
    });
  },

  // 更新订单状态（调用云函数）
  async updateOrderStatus(orderId, processStatus, successMessage) {
    try {
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction', // 云函数名称
        data: {
          updateOrderStatusRequest: {
            orderId, // 订单 ID
            processStatus, // 新的订单状态
          }
        },
      });

      if (res.result.code === 200) {
        // 更新本地状态
        const updatedOrders = this.data.orders.map((item) => {
          if (item.orderId === orderId) {
            return {
              ...item,
              processStatus, // 更新状态
            };
          }
          return item;
        });

        this.setData({ orders: updatedOrders });
        wx.showToast({ title: successMessage, icon: 'success' });
        
        // 刷新订单统计数据
        this.loadOrderStatistics();
        
        return true;
      } else {
        wx.showToast({
          title: res.result.message || '状态更新失败',
          icon: 'none',
        });
        return false;
      }
    } catch (error) {
      console.error('更新订单状态失败:', error);
      wx.showToast({ title: '网络错误，状态更新失败', icon: 'none' });
      return false;
    }
  },

  // 打印完成
  printed(e) {
    const { id: orderId } = e.currentTarget.dataset;
    console.log('打印完成:', orderId);
    
    // 验证订单是否存在
    const order = this.data.orders.find((item) => item.orderId === orderId);
    if (!order) {
      wx.showToast({ title: '订单信息未找到', icon: 'none' });
      return;
    }

    // 验证订单状态是否可以执行打印完成操作
    const validStatuses = ['待打印', '打印中'];
    if (!validStatuses.includes(order.processStatus)) {
      wx.showToast({
        title: '当前状态无法执行此操作',
        icon: 'none'
      });
      return;
    }

    // 显示确认对话框
    wx.showModal({
      title: '确认操作',
      content: '确认订单打印已完成？',
      success: async (res) => {
        if (res.confirm) {
          // 调用状态更新
          const success = await this.updateOrderStatus(orderId, "待送达", "订单更新为待送达");
          
          // 如果状态更新失败，尝试重新加载订单列表
          if (!success) {
            console.log('状态更新失败，尝试重新加载订单列表');
            this.loadOrders();
          }
        }
      }
    });
  },

  // 处理投诉
  async resolveComplaint(e) {
    const { id: orderId } = e.currentTarget.dataset;
    console.log('========== 处理投诉开始 ==========');
    console.log('订单ID:', orderId);
    
    if (!orderId) {
      wx.showToast({
        title: '订单ID不能为空',
        icon: 'none'
      });
      return;
    }

    try {
      // 显示确认对话框
      const res = await new Promise((resolve) => {
        wx.showModal({
          title: '确认处理',
          content: '确定要将此投诉标记为已处理吗？',
          success: resolve
        });
      });

      if (!res.confirm) {
        console.log('用户取消处理投诉');
        return;
      }

      // 调用云函数更新投诉状态
      const updateRes = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          updateComplaintStatusRequest: {
            orderId: orderId,
            complaintDealStatus: '已处理'
          }
        }
      });

      console.log('云函数返回结果:', updateRes.result);

      if (updateRes.result && updateRes.result.code === 200) {
        wx.showToast({
          title: '处理成功',
          icon: 'success'
        });
        
        // 重新加载投诉列表
        this.loadComplaints();
      } else {
        wx.showToast({
          title: updateRes.result?.message || '处理失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('处理投诉失败:', error);
      wx.showToast({
        title: '处理失败',
        icon: 'none'
      });
    }
  },

  // 联系客户
  callCustomer(e) {
    const { phone } = e.currentTarget.dataset;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone,
        fail: () => {
          wx.showToast({
            title: '拨号失败',
            icon: 'none'
          });
        }
      });
    }
  },

  // 预览图片
  previewImage(e) {
    const { src } = e.currentTarget.dataset;
    if (src) {
      wx.previewImage({
        urls: [src],
        current: src
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      page: 1,
      orders: []
    });
    
    // 保持搜索状态
    const searchKeyword = this.data.searchKeyword;
    this.loadOrders(searchKeyword);
    
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.orders.length < this.data.total) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadOrders();
    }
  },

  // 获取产品列表
  async fetchProductList() {
    console.log('========== fetchProductList 方法开始执行 ==========');
    try {
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress?.addressCode;
      console.log('获取产品列表，学校代码:', schoolCode);
      console.log('完整地址信息:', selectedAddress);
      
      const res = await wx.cloud.callFunction({
        name: 'xiaoBangCommonFunction',
        data: {
          getProductListRequest: {
            schoolCode: schoolCode
          }
        }
      });

      console.log('获取产品列表响应:', res.result);

      if (res.result && res.result.code === 200) {
        const products = res.result.data.products || [];
        console.log('从云函数获取到的产品:', products);
        
        // 转换产品数据格式，只保留必要信息，不显示图标
        const productTypes = products.map(product => {
          console.log('处理产品:', product.productTitle, '产品ID:', product.productId);
          return {
            id: product.productId,
            name: product.productTitle,
            color: this.getProductColor(product.productId),
            desc: product.productDesc || ''
          };
        });

        // 添加"所有订单"选项
        productTypes.unshift({
          id: 'allOrders',
          name: '所有订单',
          color: '#795548',
          desc: '查看所有类型的订单'
        });

        // 如果商家有零食代买权限，但云端产品未返回，则补充一个“零食代买”选项
        try {
          const { permissions } = this.data;
          const hasSnackPermission = !!permissions?.PSnackPickup;
          const existsSnack = productTypes.some(p => p.id === 'PSnackPickup');
          if (hasSnackPermission && !existsSnack) {
            productTypes.push({
              id: 'PSnackPickup',
              name: '零食代买',
              color: this.getProductColor('PSnackPickup'),
              desc: '零食代买订单'
            });
          }
        } catch (e) {
          console.warn('ensure PSnackPickup option failed:', e);
        }

        this.setData({
          productTypes: productTypes
        }, () => {
          // 产品列表设置完成后，重新初始化下拉菜单
          this.initProductDropdown();
        });
        console.log('产品列表设置成功:', productTypes);
      } else {
        console.error('获取产品列表失败:', res.result?.message || '未知错误');
        console.error('错误详情:', res.result);
        
        // 显示错误提示
        wx.showToast({
          title: `获取产品列表失败: ${res.result?.message || '未知错误'}`,
          icon: 'none',
          duration: 3000
        });
        
        // 使用默认产品列表
        this.setData({
          productTypes: this.data.defaultProductTypes
        }, () => {
          this.initProductDropdown();
        });
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
      // 使用默认产品列表
      this.setData({
        productTypes: this.data.defaultProductTypes
      }, () => {
        this.initProductDropdown();
      });
    }
  },

  // 根据产品ID获取图标
  getProductIcon(productId) {
    const iconMap = {
      'PPacakgePickUp': '📦',
      'PSnackPickup': '🍫',
      'PWashShoes': '👟',
      'PWashClothes': '👕',
      'PPaoTui': '🏃',
      'PPrintBlackAndWhite': '🖨️'
    };
    return iconMap[productId] || '📦';
  },

  // 根据产品ID获取颜色
  getProductColor(productId) {
    const colorMap = {
      'PPacakgePickUp': '#4CAF50',
      'PSnackPickup': '#F06292',
      'PWashShoes': '#2196F3',
      'PWashClothes': '#FF9800',
      'PPaoTui': '#9C27B0',
      'PPrintBlackAndWhite': '#607D8B'
    };
    return colorMap[productId] || '#4CAF50';
  },

  // 格式化金额，避免浮点数精度问题
  formatAmount(amount) {
    if (typeof amount === 'string') {
      amount = parseFloat(amount);
    }
    if (isNaN(amount)) {
      return 0;
    }
    // 保留2位小数，避免浮点数精度问题
    return Math.round(amount * 100) / 100;
  },

  // 显示退款弹窗
  showRefundModal(e) {
    const orderId = e.currentTarget.dataset.id;
    const amount = parseFloat(e.currentTarget.dataset.amount) || 0;
    const status = e.currentTarget.dataset.status;
    
    // 检查订单状态，只有已支付的订单才能退款
    if (status === '待支付') {
      wx.showToast({
        title: '待支付订单无法退款',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showRefundModal: true,
      refundData: {
        orderId: orderId,
        totalAmount: amount,
        orderStatus: status,  // 新增：传递订单状态
        refundType: 'full',
        refundAmount: amount,
        refundReason: '',
        rejectReason: ''      // 新增：拒绝原因
      }
    });
  },

  // 隐藏退款弹窗
  hideRefundModal() {
    this.setData({
      showRefundModal: false,
      refundData: {
        orderId: this.data.refundData.orderId, // 保留订单号，不清空
        totalAmount: 0,
        orderStatus: '',     // 重置订单状态
        refundType: 'full',
        refundAmount: 0,
        refundReason: '',
        rejectReason: ''     // 重置拒绝原因
      }
    });
  },

  // 选择退款类型
  selectRefundType(e) {
    const type = e.currentTarget.dataset.type;
    const refundData = { ...this.data.refundData };
    refundData.refundType = type;
    
    if (type === 'full') {
      refundData.refundAmount = refundData.totalAmount;
    } else {
      refundData.refundAmount = 0;
    }
    
    this.setData({
      refundData: refundData
    });
  },

  // 退款金额输入
  onRefundAmountInput(e) {
    const value = e.detail.value;
    console.log('退款金额输入:', value);
    
    const maxAmount = this.data.refundData.totalAmount;
    
    // 直接保存用户输入的原始值，不进行parseFloat转换
    // 这样用户可以输入"0.1"、"0.2"等小数
    let finalValue = value;
    
    // 只有在用户输入完成时（比如失去焦点）才进行数值验证
    // 这里我们只做基本的格式检查
    if (value && value.trim() !== '') {
      // 检查是否是有效的数字格式（包括小数）
      const numberRegex = /^\d*\.?\d*$/;
      if (!numberRegex.test(value)) {
        // 如果不是有效数字格式，保持原值让用户继续输入
        finalValue = value;
      } else {
        // 如果是有效数字格式，检查是否超过最大值
        const amount = parseFloat(value);
        if (!isNaN(amount) && amount > maxAmount) {
          finalValue = maxAmount.toString();
        } else {
          finalValue = value;
        }
      }
    }
    
    console.log('最终值:', finalValue, '最大金额:', maxAmount);
    
    this.setData({
      'refundData.refundAmount': finalValue
    });
  },

  // 退款原因输入
  onRefundReasonInput(e) {
    this.setData({
      'refundData.refundReason': e.detail.value
    });
  },

  // 拒绝原因输入
  onRejectReasonInput(e) {
    this.setData({
      'refundData.rejectReason': e.detail.value
    });
  },

  // 确认退款
  confirmRefund() {
    const { orderId, refundType, refundAmount, refundReason, rejectReason, totalAmount } = this.data.refundData;
    
    // 如果是拒绝退款
    if (refundType === 'reject') {
      // 验证拒绝原因
      if (!rejectReason || rejectReason.trim() === '') {
        wx.showToast({
          title: '请输入拒绝原因',
          icon: 'none'
        });
        return;
      }
      
      // 显示确认对话框
      wx.showModal({
        title: '确认拒绝退款',
        content: `确定要拒绝订单 ${orderId} 的退款申请吗？`,
        success: (res) => {
          if (res.confirm) {
            this.processRejectRefund();
          }
        }
      });
      return;
    }
    
    // 原有的退款逻辑
    // 解析退款金额为数字
    const refundAmountNum = parseFloat(refundAmount);
    
    // 验证退款金额
    if (refundType === 'partial' && (isNaN(refundAmountNum) || refundAmountNum <= 0)) {
      wx.showToast({
        title: '请输入有效的退款金额',
        icon: 'none'
      });
      return;
    }
    
    if (refundAmountNum > totalAmount) {
      wx.showToast({
        title: '退款金额不能超过订单金额',
        icon: 'none'
      });
      return;
    }
    
    // 显示确认对话框
    const refundTypeText = refundType === 'full' ? '全部退款' : '部分退款';
    wx.showModal({
      title: '确认退款',
      content: `确定要对订单 ${orderId} 进行${refundTypeText}吗？退款金额：¥${refundAmountNum}`,
      success: (res) => {
        if (res.confirm) {
          this.processRefund();
        }
      }
    });
  },

  // 更新单个订单信息
  async updateSingleOrder(orderId) {
    try {
      console.log('========== updateSingleOrder 开始更新订单 ==========');
      console.log('订单ID:', orderId);
      
      const selectedAddress = wx.getStorageSync('selectedAddress');
      const schoolCode = selectedAddress && selectedAddress.addressCode ? selectedAddress.addressCode : null;

      // 调用云函数获取单个订单的最新信息
      const res = await wx.cloud.callFunction({
        name: "xiaoBangCommonFunction",
        data: {
          getOrderListForManageRequest: {
            page: 1,
            pageSize: 1,
            orderType: this.data.selectedProductType === 'allOrders' ? null : this.data.selectedProductType,
            schoolCode: schoolCode,
            orderId: orderId // 只获取指定订单
          }
        },
      });

      if (res.result.code === 200) {
        const { orders } = res.result.data;
        
        if (orders && orders.length > 0) {
          const updatedOrder = orders[0];
          
          // 处理订单数据（复用 loadOrders 中的数据处理逻辑）
          updatedOrder.orderType = this.getOrderTypeByProductId(updatedOrder);
          updatedOrder.paoTuiPickupAddress = updatedOrder.pao_tui_pickup_address;
          updatedOrder.paoTuiPickupTime = updatedOrder.pao_tui_pickup_time;
          updatedOrder.paoTuiDeliveryAddress = updatedOrder.pao_tui_delivery_address;
          updatedOrder.paoTuiDeliveryTime = updatedOrder.pao_tui_delivery_time;
          updatedOrder.paoTuiNote = updatedOrder.paoTuiNote;
          
          // 处理快递代取信息
          if (updatedOrder.packagePickupInfos && updatedOrder.packagePickupInfos.length > 0) {
            updatedOrder.packagePickupInfos = updatedOrder.packagePickupInfos.map(info => ({
              pickupAddress: info.pickupAddress || info.pickup_address,
              pickupCode: info.pickupCode || info.pickup_code,
              pickupSize: info.pickupSize || info.pickup_size,
              photos: info.photos || []
            }));
          }
          
          // 处理洗鞋图片信息
          updatedOrder.beforeCleaningPhotos = updatedOrder.beforeCleaningPhotos || updatedOrder.before_cleaning_photos || [];
          updatedOrder.afterCleaningPhotos = updatedOrder.afterCleaningPhotos || updatedOrder.after_cleaning_photos || [];
          
          // 处理送达图片信息
          updatedOrder.deliveredPhotos = updatedOrder.deliveredPhotos || updatedOrder.delivered_photos || [];
          
          // 处理退款信息
          const rawRefundAmount = updatedOrder.refundAmount || updatedOrder.refund_amount || 0;
          updatedOrder.refundAmount = this.formatAmount(rawRefundAmount);
          updatedOrder.refundReason = updatedOrder.refundReason || updatedOrder.refund_reason || '';
          updatedOrder.refundType = updatedOrder.refundType || updatedOrder.refund_type || '';
          
          // 兼容历史数据：如果订单状态是已退款但没有refund_type字段，自动设置
          if (updatedOrder.orderStatus === '已退款' && !updatedOrder.refundType) {
            updatedOrder.refundType = 'full';
          } else if (updatedOrder.orderStatus === '部分退款' && !updatedOrder.refundType) {
            updatedOrder.refundType = 'partial';
          }
          
          // 更新订单列表中的对应订单
          const updatedOrders = this.data.orders.map(order => {
            if (order.orderId === orderId) {
              return updatedOrder;
            }
            return order;
          });
          
          this.setData({
            orders: updatedOrders
          });
          
          console.log('订单更新成功:', orderId);
        } else {
          console.log('未找到订单:', orderId);
        }
      } else {
        console.error('获取订单信息失败:', res.result.message);
      }
    } catch (error) {
      console.error("更新订单信息失败：", error);
    }
  },

  // 处理退款
  processRefund() {
    const { orderId, refundType, refundAmount, refundReason } = this.data.refundData;
    
    // 确保退款金额是数字类型
    const refundAmountNum = parseFloat(refundAmount);
    
    wx.showLoading({
      title: '处理退款中...'
    });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        processRefundRequest: {
          orderId: orderId,
          refundType: refundType,
          refundAmount: refundAmountNum,
          refundReason: refundReason
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('退款处理结果:', res);
        
        if (res.result && res.result.code === 200) {
          wx.showToast({
            title: '退款处理成功',
            icon: 'success'
          });
          
          // 关闭弹窗
          this.hideRefundModal();
          
          // 只更新指定订单信息，不重新加载整个列表
          this.updateSingleOrder(orderId);
        } else {
          wx.showToast({
            title: res.result?.message || '退款处理失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('退款处理失败:', err);
        wx.showToast({
          title: '退款处理失败',
          icon: 'none'
        });
      }
    });
  },

  // 处理拒绝退款
  processRejectRefund() {
    const { orderId, rejectReason } = this.data.refundData;
    
    wx.showLoading({
      title: '处理拒绝中...'
    });
    
    wx.cloud.callFunction({
      name: 'xiaoBangCommonFunction',
      data: {
        updateOrderStatusRequest: {
          orderId: orderId,
          rejectRefund: true,
          rejectReason: rejectReason
        }
      },
      success: (res) => {
        wx.hideLoading();
        console.log('拒绝退款处理结果:', res);
        
        if (res.result && res.result.code === 200) {
          wx.showToast({
            title: '拒绝退款成功',
            icon: 'success'
          });
          
          // 关闭弹窗
          this.hideRefundModal();
          
          // 只更新指定订单信息，不重新加载整个列表
          this.updateSingleOrder(orderId);
        } else {
          wx.showToast({
            title: res.result?.message || '拒绝退款失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('拒绝退款处理失败:', err);
        wx.showToast({
          title: '拒绝退款失败',
          icon: 'none'
        });
      }
    });
  }
});